package com.atguigu.flinkSql2;




import com.atguigu.been.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.annotation.DataTypeHint;
import org.apache.flink.table.annotation.FunctionHint;
import org.apache.flink.table.annotation.FunctionHints;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.*;


/**
 * @author wky
 * @create 2021-07-22-10:40
 */

// 表函数 UDTF 一进多出
public class Flink07_UDTF_TableFuntion {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);
        //将默认时区从格林威治时区改为东八区
        Configuration configuration = tableEnvironment.getConfig().getConfiguration();
        configuration.setString("table.local-time-zone", "GMT");
        //2.读取文件得到DataStream
        DataStreamSource<WaterSensor> waterSensorDataStreamSource = env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_1", 2000L, 20),
                new WaterSensor("sensor_2", 3000L, 30),
                new WaterSensor("sensor_1", 4000L, 40),
                new WaterSensor("sensor_1", 5000L, 50),
                new WaterSensor("sensor_2", 6000L, 60));

        //3.将流转换为动态表
        Table table = tableEnvironment.fromDataStream(waterSensorDataStreamSource);


//        //不注册函数直接使用 只能在tableApi中使用
//        table
//                .joinLateral(call(MySplit.class,$("id")))
//                .select($("id"),$("word")).execute().print();


//        注册函数 再使用 可以在sql语句中
        tableEnvironment.createTemporarySystemFunction("split",MySplit.class);
//        table
//                .joinLateral(call("split",$("id")))
//                .select($("id"),$("word"))
//                .execute().print();
        //基本不用
//        tableEnvironment.executeSql(
//                "select id ,word from "+table+ " join lateral table (split(id)) on true"
//        ).print();
        //todo sql 开窗 写法
        tableEnvironment.executeSql("select id , word from " +table+ " ,lateral table (split(id))").print();


    }
    //自定义UDTF函数将传入的id按照下划线炸裂成两条数据
    //hint暗示，主要作用为类型推断时使用

    @FunctionHint(output = @DataTypeHint("Row<word String>"))
    public static class MySplit extends TableFunction<Row> {
        public void eval(String value){
            for (String s : value.split("_")) {
                collect(Row.of(s));
            }
        }

    }
}
